<template>
  <div>
    <el-card class='box-card' shadow='always'>
      <div slot='header' class='clearfix'>
        <b>
          <svg-icon icon-class='menu' />
          菜单列表</b>
      </div>
      <!-- 搜索表单 -->
      <el-form ref='queryForm' :inline='true' :model='queryParams' size='mini'>
        <el-form-item>
          <el-button
            v-has-permission="['sys:menu:add']"
            icon='el-icon-plus'
            type='success'
            @click='handleAdd'
          >新增
          </el-button>
        </el-form-item>
        <el-form-item>
          <el-input
            v-model='queryParams.name'
            clearable
            placeholder='菜单名称'
            @keyup.enter.native='handleQuery'
          />
        </el-form-item>
        <el-form-item>
          <el-button
            icon='el-icon-search'
            type='primary'
            @click='handleQuery'
          >搜索
          </el-button>
          <el-button
            icon='el-icon-refresh'
            @click='handleReset'
          >重置
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 数据表格 -->
      <el-table
        v-loading='loading'
        :data='pageList'
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        border
        highlight-current-row
        row-key='id'
        size='mini'
        @row-click='handleRowClick'
      >
        <el-table-column label='菜单名称'>
          <template slot-scope='scope'>
            <template v-if="scope.row.icon !== undefined && scope.row.icon.includes('el-icon')">
              <i :class='scope.row.icon' />
            </template>
            <template v-else>
              <svg-icon :icon-class="scope.row.icon ? scope.row.icon : 'build'" />
            </template>
            {{ scope.row.name }}
          </template>
        </el-table-column>
        <el-table-column align='center' label='操作' width='130'>
          <template slot-scope='scope'>
            <el-button
              v-has-permission="['sys:menu:add']"
              circle
              icon='el-icon-plus'
              plain
              size='mini'
              type='success'
              @click.stop='handleAdd(scope.row)'
            />
            <el-button
              v-has-permission="['sys:menu:edit']"
              circle
              icon='el-icon-edit'
              plain
              size='mini'
              type='primary'
              @click.stop='handleEdit(scope.row)'
            />
            <el-button
              v-has-permission="['sys:menu:delete']"
              circle
              icon='el-icon-delete'
              plain
              size='mini'
              type='danger'
              @click.stop='handleDelete(scope.row)'
            />
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog :title='dialog.title' :visible.sync='dialog.visible' width='200'>
      <el-form ref='form' :model='form' :rules='rules' label-width='120px'>
        <el-form-item label='上级菜单' prop='parentId'>
          <tree-select
            v-model='form.parentId'
            :options='menuOptions'
            placeholder='选择上级菜单'
            @select='handleMenuSelect'
          />
        </el-form-item>

        <el-form-item label='菜单类型' prop='type'>
          <el-radio-group v-model='form.type' :disabled='form.parentId === 0'>
            <el-radio :label='0'>目录</el-radio>
            <el-radio :label='1'>菜单</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label='菜单名称' prop='title'>
          <el-input v-model='form.title' placeholder='请输入菜单名称' />
        </el-form-item>

        <el-form-item label='路由名称' prop='name'>
          <el-input
            v-model='form.name'
            placeholder='system_user'
            style='width: 95%'
          />
          <el-tooltip
            content="vue-router编程式路由跳转方式之一，例：this.$router.push({name:'system_user',params:{id:1}})"
            effect='dark'
            placement='right'
          >
            <i
              class='el-icon-info'
              style='margin-left: 5px;color:darkseagreen'
            />
          </el-tooltip>
        </el-form-item>

        <el-form-item label='路由路径' prop='routePath'>
          <el-input
            v-model='form.path'
            :placeholder="form.parentId === 0 ? '/system' : 'user'"
            style='width: 95%'
          />
          <el-tooltip
            content="vue-router编程式路由跳转方式之一，例：this.$router.push({path:'/system/user',query:{id:1}})"
            effect='dark'
            placement='right'
          >
            <i
              class='el-icon-info'
              style='margin-left: 5px;color:darkseagreen'
            />
          </el-tooltip>
        </el-form-item>

        <el-form-item v-if='form.type === 1' label='组件路径' prop='component'>
          <el-input
            v-model='form.component'
            placeholder='system/user/index'
          >
            <template
              v-if='form.parentId !== 0'
              slot='prepend'
            >src/views/
            </template>
            <template v-if='form.parentId !== 0' slot='append'>.vue</template>
          </el-input>
        </el-form-item>

        <el-form-item label='菜单图标'>
          <el-popover
            placement='bottom-start'
            trigger='click'
            width='460'
            @show="$refs['iconSelect'].reset()"
          >
            <IconSelect ref='iconSelect' @selected='handleIconSelected' />
            <el-input
              slot='reference'
              v-model='form.icon'
              placeholder='点击选择图标'
            >
              <svg-icon
                v-if='form.icon'
                slot='prefix'
                :icon-class='form.icon'
                class='el-input__icon'
                style='height: 40px;width: 16px; '
              />
              <i v-else slot='prefix' class='el-icon-search el-input__icon' />
            </el-input>
          </el-popover>
        </el-form-item>

        <el-form-item label='缓存' prop='keepAlive'>
          <el-radio-group v-model='form.keepAlive'>
            <el-radio :label='true'>开启</el-radio>
            <el-radio :label='false'>关闭</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label='状态' prop='hidden'>
          <el-radio-group v-model='form.hidden'>
            <el-radio :label='false'>显示</el-radio>
            <el-radio :label='true'>隐藏</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label='固定面包屑' prop='affix'>
          <el-radio-group v-model='form.affix'>
            <el-radio :label='true'>是</el-radio>
            <el-radio :label='false'>否</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label='隐藏面包屑' prop='hideHeader'>
          <el-radio-group v-model='form.hideHeader'>
            <el-radio :label='true'>是</el-radio>
            <el-radio :label='false'>否</el-radio>
          </el-radio-group>
        </el-form-item>

        <template v-if='form.type === 0'>
          <el-form-item label='固定显示根菜单' prop='alwaysShow'>
            <el-radio-group v-model='form.alwaysShow'>
              <el-radio :label='true'>是</el-radio>
              <el-radio :label='false'>否</el-radio>
            </el-radio-group>
          </el-form-item>
        </template>

        <el-form-item label='排序' prop='sort'>
          <el-input-number
            v-model='form.sort'
            :min='0'
            controls-position='right'
            style='width: 100px'
          />
        </el-form-item>

        <el-form-item label='跳转路径'>
          <el-input
            v-model='form.redirect'
            maxlength='50'
            placeholder='请输入跳转路径'
          />
        </el-form-item>
      </el-form>
      <div slot='footer' class='dialog-footer'>
        <el-button type='primary' @click='handleSubmit'>确 定</el-button>
        <el-button @click='closeDialog'>取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import TreeSelect from '@riophae/vue-treeselect'
import IconSelect from '@/components/IconSelect/icons'
import { add, del, list, update, updateStatus } from '@/api/admin/menu'

export default {
  name: 'Menu',
  components: { TreeSelect, IconSelect },
  data() {
    return {
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      queryParams: {
        name: undefined,
        queryMode: undefined
      },
      pageList: [],
      dialog: {
        title: undefined,
        visible: false
      },
      form: {
        parentId: 0,
        hidden: false,
        icon: undefined,
        sort: 1,
        component: 'Layout',
        title: undefined,
        name: undefined,
        path: undefined,
        redirect: undefined,
        keepAlive: true,
        alwaysShow: false,
        affix: false,
        hideHeader: false,
        level: 1,
        type: 0
      },
      rules: {
        parentId: [
          { required: true, message: '请选择顶级菜单', trigger: 'blur' }
        ],
        name: [{ required: true, message: '请输入菜单名称', trigger: 'blur' }]
      },
      title: '新增菜单',
      menuOptions: [],
      currentRow: undefined
    }
  },
  async created() {
    this.loadMenuOptions()
    this.handleQuery()
  },
  methods: {
    handleQuery() {
      this.resetForm()
      this.queryParams.queryMode = 'list'
      list(this.queryParams).then(({ data }) => {
        this.pageList = data
        this.loading = false
      })
    },
    handleReset() {
      this.pagination = {
        page: 1,
        limit: 10,
        total: 0
      }
      this.queryParams.name = undefined
      this.handleQuery()
      this.loadMenuOptions()
    },
    handleRowClick(row) {
      const currentRow = JSON.parse(JSON.stringify(row))
      console.log('选中菜单', currentRow)
      this.currentRow = currentRow
      this.form = currentRow
      this.title = '修改菜单'
      this.$emit('menuClick', row)
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    handleStatusChange(row) {
      const text = row.status === 1 ? '启用' : '停用'
      this.$confirm('确认要"' + text + row.name + '"数据项吗?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(function() {
          return updateStatus(row.id, { status: row.status })
        })
        .then(() => {
          this.$message.success(text + '成功')
        }).finally(() => {
          this.handleQuery()
        })
    },

    handleAdd(row) {
      this.resetForm()
      this.dialog = {
        title: '新增菜单',
        visible: true
      }
      if (row.id) {
        // 行点击新增
        this.form.level = row.level + 1
        this.form.parentId = row.id
        this.form.component = undefined
      } else {
        // 工具栏点击新增
        if (this.currentRow) {
          this.form.parentId = this.currentRow.id
          this.form.component = undefined
        } else {
          this.form.parentId = 0
          this.form.component = 'Layout'
        }
      }
      this.title = '新增菜单'
    },
    handleEdit(row) {
      this.resetForm()
      this.dialog = {
        title: '修改菜单',
        visible: true
      }
      this.form = row
    },
    handleSubmit: function() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          const id = this.form.id
          if (this.form.level !== 1 && this.form.type === 0) {
            this.form.component = 'nested/index'
          }
          if (id !== undefined) {
            update(this.form).then(() => {
              this.$message.success('修改成功')
              this.handleQuery()
              this.loadMenuOptions()
              this.closeDialog()
            })
          } else {
            add(this.form).then(() => {
              this.$message.success('新增成功')
              this.handleQuery()
              this.loadMenuOptions()
              this.closeDialog()
            })
          }
        }
      })
    },
    handleDelete(row) {
      // const ids = [row.id || this.ids].join(',')
      const ids = row.id ? [row.id] : this.ids
      this.$confirm('确认删除已选中的数据项？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          del(ids).then(() => {
            this.$message.success('删除成功')
            this.handleQuery()
            this.loadMenuOptions()
          })
        })
        .catch(() => this.$message.info('已取消删除'))
    },
    resetForm() {
      this.form = {
        parentId: 0,
        hidden: false,
        icon: undefined,
        sort: 1,
        component: 'Layout',
        title: undefined,
        name: undefined,
        path: undefined,
        redirect: undefined,
        keepAlive: true,
        alwaysShow: false,
        affix: false,
        hideHeader: false,
        level: 1,
        type: 0
      }
    },
    loadMenuOptions() {
      this.menuOptions = []
      list({ queryMode: 'tree' }).then(response => {
        const menuOption = { id: 0, label: '无', children: response.data }
        this.menuOptions.push(menuOption)
        this.$forceUpdate()
      })
    },
    handleIconSelected(name) {
      this.form.icon = name
      this.$forceUpdate()
    },
    handleMenuSelect(node) {
      if (node.level === undefined) {
        this.form.level = 1
      } else {
        this.form.level = node.level + 1
      }
      if (node.id === 0) {
        this.form.component = 'Layout'
      } else {
        this.form.component = undefined
      }
    },
    closeDialog() {
      this.resetForm()
      this.dialog = {
        title: undefined,
        visible: false
      }
    }
  }
}
</script>

<style scoped></style>
